package org.jet.emall.security.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-07 19:31
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {


    private Boolean postOnly = true;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        //如果请求不是POST请求，且要求POST请求，则抛异常
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String username=null;
        String password=null;

        // 原来的UsernamePasswordAuthenticationFilter中是从请求参数
        // 中取出用户名和密码，而现在前后端分离，我们把用户名和密码以json格式放在请求体中
        try {
            JSONObject object = JSON.parseObject(readRequestBody(request));
            username = object.getString(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY);
            password = object.getString(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY);
        } catch (IOException e) {
            e.printStackTrace();
        }


        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);
        //调用相关组件去完成用户信息的加载和密码校验等工作
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    /**
     * 从请求体中读出字符串
     * @param request
     * @return
     */
    private String readRequestBody(HttpServletRequest request) throws IOException {
        BufferedReader reader = request.getReader();
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line=reader.readLine())!=null){
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }

}
